package net.dlz.example.controller;

import net.dlz.example.domain.News;
import net.dlz.example.domain.SearchNewsResponse;
import net.dlz.example.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;


@Controller
@RequestMapping("/News")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @RequestMapping("/nlist")
    public String NewsList(Model model){
        List<News> newss =newsService.listNews();
        model.addAttribute("newss",newss);
        return "news_list";}

    @RequestMapping("/nalist")
    public String NewsAdminList(){return "newsadmin_list";}

    @GetMapping("/api/search")
    @ResponseBody
    public SearchNewsResponse searchNewsResponse(@RequestParam("pageNum") Integer pageNum,
                                                 @RequestParam("pageSize") Integer pageSize){
        return newsService.findAllNews(pageNum,pageSize);
    }

    @GetMapping("/api/searchLink")
    @ResponseBody
    public SearchNewsResponse searchNewsResponseLink(@RequestParam("keywords") String keywords,
                                                     @RequestParam("pageNum") Integer pageNum,
                                                     @RequestParam("pageSize") Integer pageSize){
        return newsService.findNewsLinkTopic(keywords,pageNum,pageSize);
    }
    @RequestMapping("/toadd")
    public String addnewsPage(Model model){
        model.addAttribute("news",new News());
        return "news_submit";
    }
    @RequestMapping("/add")
    public String addNews(News news){
        int updated = newsService.saveNews(news);
        return "redirect:/News/list";
    }




    @DeleteMapping("/delete")
    @ResponseBody
    public Boolean deleteArea(@RequestParam("id") String id){
        int deleted = newsService.deleteNews(id);
        return deleted > 0;
    }

    @RequestMapping("/content")
        public String NewsContent(@RequestParam("id") String id,Model model){
            News news = newsService.findNewsByPrimaryKey(id);
            model.addAttribute("news",news);
            return "news_content";
    }

}
